<!--
*@Author: QWP
*@Description: 创建群聊
*@Date: 2024-07-08 17:04:38
-->
<template>
  <a-layout class="f-h-100">
    <a-layout-content class="s-bg-white" style="overflow: auto">
      <a-space direction="vertical">
        <u-busi-card title="" :bordered="false">
          <u-form 
            :elements="formEls" 
            :model="form" 
            :gutter="0"
            :loading="loading" 
            ref="formRef">
            <template #groupUser>
              <a-tree-select
                v-model:value="form.groupUser"
                style="width: 100%"
                :tree-data="deptUsers"
                :fieldNames="{ label: 'name', value: 'keyid', children: 'children' }" 
                tree-checkable
                allow-clear
                placeholder="请选择群成员"
                tree-node-filter-prop="label"
              />
            </template>
          </u-form>
        </u-busi-card>
      </a-space>
    </a-layout-content>
  </a-layout>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, watch, useAttrs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useLoginStore, useBaseStore } from '@/store'
import { storeToRefs } from 'pinia'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { messageC } from '@/util/common';
import * as groupApi from '@/service/emergency/group'
import * as unitApi from '@/service/system/unit'
import * as travelApi from "@/service/administration/travel";
import * as emergencyWarningApi from '@/service/emergencyWarning/index'
import dayjs from 'dayjs'

const props = defineProps<{
  keyid?: string
}>()

const route = useRoute()
const attrs = useAttrs()
const emits = defineEmits(['success'])

const { userInfo } = storeToRefs(useLoginStore())
const { unitData, deptUsers } = storeToRefs(useBaseStore())

const formRef = ref<FormInstance>()
const loading = ref<boolean>(false)
const form = ref({})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '90px',
  colon: false
}
// 1848609862771183618
const formEls: Array<_IFormEl> = reactive([
  {
    label: '群名称', key: 'groupNames', col: { span: 24, }, element: 'input',
    formItemProps: { ...formItemProps, required: true }
  },
  {
    label: '申请单位', key: 'appUnit', col: { span: 12 }, element: 'select',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      fieldNames: { label: 'name', value: 'keyid' },
      options: computed(() => unitData.value)
    }
  },
  {
    label: '申请人', key: 'appUser1', col: { span: 12 }, element: 'input',
    formItemProps: { ...formItemProps, required: true }
  },
  {
    label: '群成员', key: 'groupUser', col: { span: 24 }, element: 'slot',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      treeCheckable: true,
      treeData: deptUsers.value,
      fieldNames: { label: 'name', value: 'keyid', children: 'children' },
    }
  },
  {
    label: '联系电话', key: 'telNo', col: { span: 12 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
  },
  {
    label: '人员类型', key: 'userType', col: { span: 12 }, element: 'input',
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      maxlength: 10,
      showCount: true
    }
  },
  {
    label: '申请时间', key: 'appTime', col: { span: 12 }, element: 'datepicker',
    formItemProps: { ...formItemProps, required: true }
  },
])

// 初始化表单信息
const initForm = () => {
  form.value = {
    appUnit: userInfo.value['unitId'],
    appUser1: userInfo.value['name'],
    appUser: userInfo.value['userId'],
    telNo: userInfo.value['tel'],
    appTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  }
}

// 获取部门人员树
const lev1Keyids = computed(() => {
  let keyids = deptUsers.value.map(item => item.keyid);
  keyids.push(userInfo.value['userId']) // 建群人id
  return keyids
})

// 提交保存
const submit = async () => {
  await formRef.value.form.validate();
  loading.value = true;
  try {
    let groupUser = (form.value['groupUser'] || []).filter(id => !lev1Keyids.value.includes(id));
    form.value.userIds = groupUser.join(',')
    const url = props.keyid ? 'update' : 'add';
    const res = await groupApi[url](form.value);
    if (res.code == 0) {
      messageC(res.msg, "success");
      dialogClose()
      emits('success', res.data)
    } else {
      if(form.value['groupLabel']) {
        delWarning(form.value['groupLabel'])
      }
      messageC(res.msg, "error");
    }
  } catch (error) { }
  loading.value = false
}

// 删除对应的风险
const delWarning = async (warningId) => {
  let ids = tabSelData.value.map(item => item.keyid);
  try {
    await emergencyWarningApi.del({ ids: warningId });
  } catch (error) {}
}

// 弹窗关闭
const dialogClose = () => {
  form.value = {};
  formRef.value.form.resetFields();
}

// 初始化显示
const initShow = async (val) => {
  initForm()
}

// 回显数据
const getEcho = async () => {
  loading.value = true;
  try {
    const res = await groupApi.query(props.keyid);
    if(res.code == 0) {
      const tData = res.data || {};
      form.value = tData;
      let taddGroups = tData['taddGroups'] || [];
      
      // 群成员
      form.value.groupUser = taddGroups.filter(i => i.fkUser != tData.createuserid).map(i => i.fkUser);
      
      // 创建人
      let createUserInfo = taddGroups.find(i => i.fkUser == tData.createuserid);
      if(createUserInfo) {
        form.value.appUser1 = createUserInfo['fkUserName'];
        form.value.appUser = createUserInfo['fkUser'];
      }
    }
  } catch (error) {}
  loading.value = false;
}

watch(() => props.keyid, (nval, oval) => {
  if(nval) {
    getEcho()
  }
}, { immediate: true })

defineExpose({
  formRef,
  form,
  loading,
  initShow,
  submit,
  dialogClose
})
</script>

<style lang='scss'></style>